<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">

      <div class="main-content-form">
        <div class="main-content-form-detail">

          <el-form-item label="Title" label-width="120px">
            <el-col :span="12">
              <el-input v-model="form.title" />
            </el-col>
          </el-form-item>

          <el-form-item label="CoverImgUrl" label-width="120px">
            <el-col :span="12">
              <el-input v-model="form.coverImgUrl" />
            </el-col>
          </el-form-item>

          <el-row>
            <el-form-item label="Topic" label-width="120px">
              <el-select v-model="form.topic" placeholder="please select topic" @change="selectChanged">
                <el-option v-for="item in form.topics" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>

            <el-form-item label-width="120px" label="Posted Time:" class="postInfo-container-item">
              <el-date-picker v-model="form.postDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss" placeholder="Select date and time" />
            </el-form-item>
          </el-row>

        </div>

        <div class="main-content-form-coverimage">
          <div class="main-content-form-coverimage-tmp" style="margin: 23% auto;max-width:120px;max-height:120px;">
            <el-image fit="cover" :src="form.coverImgUrl">
              <div slot="error" style="width:120px;height:120px">
                <el-image :lazy="true" fit="cover" src="https://i.loli.net/2020/03/01/PVzdsf3S6GHhEMD.png" />
              </div>
              <div slot="placeholder">
                未加载是显示的内容
              </div>
            </el-image>
            <span>CoverImg预览</span>
          </div>
        </div>
      </div>

      <el-form-item style="margin-bottom: 40px;" label-width="120px" label="Summary:">
        <Tinymce ref="editor" v-model="form.summary" :height="400" />
      </el-form-item>

      <el-form-item style="margin-bottom: 40px;" label-width="120px" label="Content:">
        <Tinymce ref="editor" v-model="form.content" :height="400" />
      </el-form-item>

      <el-form-item label="IsActive">
        <el-switch v-model="form.articleStatus" :active-value="1" :inactive-value="0" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">Create</el-button>
        <el-button @click="onCancel">Cancel</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
  import Tinymce from "@/components/Tinymce";
  import Upload from "@/components/Upload/SingleImage3";
  import MDinput from "@/components/MDinput";
  import Sticky from "@/components/Sticky"; // 粘性header组件
  import {
    validURL
  } from "@/utils/validate";
  import {
    fetchArticle
  } from "@/api/article";
  import {
    searchUser
  } from "@/api/remote-search";
  import Warning from "./Warning";
  import {
    CommentDropdown,
    PlatformDropdown,
    SourceUrlDropdown
  } from "./Dropdown";

  const defaultForm = {
    status: "draft",
    title: "", // 文章题目
    content: "", // 文章内容
    content_short: "", // 文章摘要
    source_uri: "", // 文章外链
    image_uri: "", // 文章图片
    display_time: undefined, // 前台展示时间
    id: undefined,
    platforms: ["a-platform"],
    comment_disabled: false,
    importance: 0
  };

  export default {
    name: "ArticleDetail",
    components: {
      Tinymce,
      MDinput,
      Upload,
      Sticky,
      Warning,
      CommentDropdown,
      PlatformDropdown,
      SourceUrlDropdown
    },
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      const validateRequire = (rule, value, callback) => {
        if (value === "") {
          this.$message({
            message: rule.field + "为必传项",
            type: "error"
          });
          callback(new Error(rule.field + "为必传项"));
        } else {
          callback();
        }
      };
      return {
        form: {
          title: "",
          postDate: "",
          topic: "",
          topics: [],
          summary: "",
          content: "",
          coverImgUrl: "https://i.loli.net/2020/03/01/PVzdsf3S6GHhEMD.png",
          articleStatus: "",
          topicId: ""
        },
        topicArray: [],
        postForm: Object.assign({}, defaultForm),
        loading: false,
        userListOptions: [],
        rules: {
          image_uri: [{
            validator: validateRequire
          }],
          title: [{
            validator: validateRequire
          }],
          content: [{
            validator: validateRequire
          }]
        },
        tempRoute: {}
      };
    },
    computed: {
      contentShortLength() {
        return this.postForm.content_short.length;
      },
      displayTime: {
        // set and get is useful when the data
        // returned by the back end api is different from the front end
        // back end return => "2013-06-25 06:59:25"
        // front end need timestamp => 1372114765000
        get() {
          return +new Date(this.postForm.display_time);
        },
        set(val) {
          this.postForm.display_time = new Date(val);
        }
      }
    },
    created() {
      var url = window.location.href;
      var url_tem = url.split('/');
      var id = url_tem[url_tem.length - 1];
      if (id) {
        this.getArticleDetails(id);
      }
      this.tempRoute = Object.assign({}, this.$route);
      this.initTopic();
    },
    methods: {
      initTopic() {
        const parms = {};
        var self = this;
        this.$get("/queryTopic", parms)
          .then(res => {
            self.form.topics = res.data.map(v => v.topic);
            self.topicArray = res.data;
            console.log(self.form.topics);
          })
          .catch(() => {});
      },
      selectChanged(value) {
        console.log(value);
      },
      onSubmit() {
        // topic处理
        if (this.topicArray) {
          for (var a in this.topicArray) {
            if (this.topicArray[a].topic == this.form.topic) {
              this.form.topicId = this.topicArray[a].id;
            }
          }
        }
        this.outputObj(this.form);

        // 扔数据
        const parms = this.form;
        var self = this;
        this.$post("/addArticle", parms)
          .then(res => {
            this.$message("submit successfully !");
          })
          .catch(() => {
            this.$message("submit failure !");
          });
      },
      onCancel() {
        this.$message({
          message: "cancel!",
          type: "warning"
        });
      },
      outputObj(obj) {
        var description = "";
        for (var i in obj) {
          description += i + " = " + obj[i] + "\n";
        }
        console.log(description);
      },
      getArticleDetails(id) {
        // var id = this.$route.query.id;
        this.getArticleById(id);
      },
      getArticleById(id) {
        let params = {
          id: id
        }
        var self = this;
        this.$get('/queryArticleById', params)
          .then(res => {
            self.form = res.data;
          })
          .catch(() => {})
      }
    }
  };

</script>

<style lang="scss" scoped>
  @import "~@/styles/mixin.scss";

  .article-textarea /deep/ {
    textarea {
      padding-right: 40px;
      resize: none;
      border: none;
      border-radius: 0px;
      border-bottom: 1px solid #bfcbd9;
    }
  }

  .main-content-form {
    display: flex;
    flex-direction: row;
  }

  .main-content-form-detail {
    width: 60%;
  }

  .main-content-form-coverimage,
  .main-content-form-coverimage-tmp {
    display: flex;
    flex-direction: column;
    padding: 20% auto;
    justify-content: center;
  }

</style>
